import React, {useState, useEffect} from 'react';
import { Select, Input } from 'antd';
import PropTypes from 'prop-types';

import api from '../../../api/index';

import style from './Filter.module.scss';

const { Option } = Select;

const Filter = (props) => {
    const {setFilterShow, setFilterDatas, filterDatas} = props;

    const [cities, setCities] = useState([]);
    const [secondCity, setSecondCity] = useState([]);
    const [layerList, setLayerList] = useState([]);

    const [filterPanelShow, setFilterPanelShow] = useState(true);           // 筛选面板显隐

    const [layerName, setLayerName] = useState('');
    const [areaMax, setAreaMax] = useState(filterDatas['areaMax']);
    const [areaMin, setAreaMin] = useState(filterDatas['areaMin']);
    const [town, setTown] = useState('');
    const [village, setVillage] = useState('');
    
    const [townLoading, setTownLoading] = useState(false);
    const [villageLoading, setVillageLoading] = useState(false);
    const [layerListLoading, setLayerListLoading] = useState(false);

    useEffect( async() => {
        // 行政区划查询
        setTownLoading(true);
        const params = {
            code: '330225000000'
        };

        api.search.queryAdmin(params)
            .then(res => {
                const {code, data = []} = res.data;
                if(code === 200) {
                    const adminData = generateAdminData(data);
                    setCities(adminData);
                    setTown(filterDatas['town']);
                    townChange(filterDatas['town'], 'init');
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                setTownLoading(false);
            })

        // 图层列表查询
        setLayerListLoading(true);
        api.search.queryLayerTree().then((res) => {
            const {code, data} = res.data;
            if(code === 200){
                const layerList = generateLayerList(data);
                setLayerList(layerList);
                setLayerName(filterDatas['code']);
            }
        }).catch(err => {
            console.log(err);
        }).finally(() => {
            setLayerListLoading(false);
        })
    },[]);

    // 关闭过滤面板
    const closeFilterPanel = () => {
        setFilterShow(false);
    };

    // 图层切换事件
    const layerChange = (val) => {
        setLayerName(val);
    };

    // 获取图层列表
    const generateLayerList = (datas) => {
        const dataList = [];

        const recursive = (datas, parentName) => {
            datas.forEach(data => {
                const {code, name, children, isClassify} = data;
                const curName = parentName ? `${parentName}-${name}` : name;
                if(!isClassify){
                    dataList.push({code, name: curName});
                }else{
                    recursive(children, curName);
                }
            });
        };

        recursive(datas,'');

        return dataList;
        
    };

    // 乡镇切换事件
    const townChange = async(val, flag) => {
        if(!val) return;

        setTown(val);
        
        setVillageLoading(true);
        const params = {
            code: val
        };

        api.search.queryAdmin(params).then((res) => {
            const {code, data} = res.data;
            if(code === 200) {
                const adminData = generateAdminData(data);
                setSecondCity(adminData);
                if(flag === 'init'){
                    setVillage(filterDatas['village']);
                }else{
                    setVillage('');
                }
            }
        }).catch((err) => {
            console.log(err);
        }).finally(() => {
            setVillageLoading(false);
        })
    };

    // 组织行政区划数据
    const generateAdminData = (datas) => {
        const adminData = datas.map(data => {
            const {code, name} = data;
            return {
                label: code,
                value: name
            }
        });
        return adminData;
    };

    // 村切换事件
    const villageChange = (val) => {
        setVillage(val);
    };

    // 最小值变化事件
    const minValueChange = (e) => {
        setAreaMin(e.target.value);
    };

    // 最大值变化事件
    const maxValueChange = (e) => {
        setAreaMax(e.target.value);
    };

    // 乡镇数据options
    const getCityOptions = cities.map(city => {
        return <Option value={city.label} key={city.value}>{city.value}</Option>
    });

    // 村数据options
    const getSecondCityOptions = secondCity.map(city => {
        return <Option value={city.label} key={city.value}>{city.value}</Option>
    });

    // 图层列表options
    const layerListOptions = layerList.map(layer => {
        const {code, name} = layer;
        return <Option value={code} key={code}>{name}</Option>
    });

    // 重置
    const reset = () => {
        setLayerName('');
        setAreaMax('');
        setAreaMin('');
        setTown('');
        setVillage('');
    };

    // 确定事件
    const sure = () => {
        const filterDatas = {};
        filterDatas.code = layerName;
        filterDatas.areaMax = areaMax;
        filterDatas.areaMin = areaMin;
        filterDatas.town = town;
        filterDatas.village = village;

        if(Object.keys(filterDatas).length > 0){
            setFilterDatas(filterDatas);
        }

        setFilterPanelShow(false);
        setFilterShow(false);
    };

    return (
        <>
            {
                filterPanelShow && 
                <div className={style.filterBox}>
                    <div className={style.header}>
                        <span>筛选</span>
                        <i className="iconfont icon-close" onClick={closeFilterPanel}></i>
                    </div>
                    <div className={style.content}>
                        <div className={style.contentItem}>
                            <span className={style.title}>图层</span>
                            <Select style={{ width: 336 }} onChange={layerChange} loading={layerListLoading} value={layerName}>
                                {layerListOptions}
                            </Select>
                        </div>
                        <div className={style.contentItem}>
                            <span className={style.title}>地区</span>
                            <div className={style.areaBox}>
                                <Select placeholder="请选择镇" style={{ width: 164, marginRight: 8 }} onChange={townChange} loading={townLoading} value={town}>
                                    {getCityOptions}
                                </Select>
                                <Select placeholder="请选择村" style={{ width: 164 }}  onChange={villageChange} loading={villageLoading} value={village}>
                                    {getSecondCityOptions}
                                </Select>
                            </div>
                        </div>
                        <div className={style.contentItem}>
                            <span className={style.title}>
                                <span>面积(公顷)</span> 
                            </span>
                            <div className={style.areaItem}>
                                <span className={style.symbol}>{'>='}</span>
                                <Input onChange={minValueChange} value={areaMin}/>
                            </div>
                            <div className={style.areaItem}>
                                <span className={style.symbol}>{'<='}</span>
                                <Input onChange={maxValueChange} value={areaMax}/>
                            </div>
                        </div>
                    </div>
                    <div className={style.bottom}>
                        <span className={style.reset} onClick={reset}>重置</span>
                        <span className={style.sure} onClick={sure}>确定</span>
                    </div>
                </div>
            }
        </>
    )
};

Filter.propTypes = {
    filterDatas: PropTypes.object,
    setFilterShow: PropTypes.func,
    setFilterDatas: PropTypes.func
};

export default Filter;